package cn.edu.zjut.medlinebackend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edu.zjut.medlinebackend.model.User;
import cn.edu.zjut.medlinebackend.service.UserService;
import cn.edu.zjut.medlinebackend.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.edu.zjut.medlinebackend.model.MessageRecordDo;
import cn.edu.zjut.medlinebackend.mapper.MessageRecordDAO;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * @author 86182
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2023-11-21 16:01:10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private MessageRecordDAO messageRecordDAO;

    @Override
    public String checkLoginValidity(User user, HttpServletResponse response) {
        User tmpUser = userMapper.getUserByUsername(user.getUsername());

        // 如果用户不存在，直接返回false
        if (tmpUser == null) {
            return "failed";
        }

        if (!Objects.equals(tmpUser.getPassword(), user.getPassword())) {
            return "failed";
        }

        if (!Objects.equals(tmpUser.getRole(), user.getRole())) {
            return "failed";
        }
        // 保存用户登录态
        Cookie cookie = new Cookie("username", user.getUsername());
        cookie.setMaxAge(3600);
        // 在jsp中，不设置cookie路径，会导致cookie失效
        cookie.setPath("/");
        response.addCookie(cookie);

        if (Objects.equals(tmpUser.getRole(), "admin")) {
            return "admin";
        } else {
            return "user";
        }
    }

    @Override
    public boolean checkIsAdmin(HttpServletRequest request) {
        //todo 添加用户权限校验
        return true;
    }

    @Override
    public boolean creatUser(User user) {
        int insert = userMapper.insert(user);
        return insert > 0;
    }

    @Override
    public List<User> searchAllUser() {
        return userMapper.selectList(null);
    }

    @Override
    public boolean deleteUserInfo(String username) {
        return userMapper.deleteByUsername(username);
    }

    @Override
    public User searchUser(String username) {
        return userMapper.getUserByUsername(username);
    }

    @Override
    public boolean updateUser(User user) {
        return userMapper.updateUserInfoByUsername(user);
    }


    public void addUserMessageRecord(MessageRecordDo messageRecordDo) {
        messageRecordDAO.addMessageRecord(messageRecordDo);
    }
}




